
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import {
  DragDropContext,
  Droppable,
  Draggable,
} from '@hello-pangea/dnd';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardFooter
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Label } from '@/components/ui/label';
import {
  Plus,
  Trash2,
  GripVertical,
  Edit3,
  ChevronDown,
  ChevronRight,
  Clock,
  Users,
  Wrench,
  Shield,
  CheckSquare,
  Leaf,
  Truck,
  Package,
  Library,
  Check,
  ChevronsUpDown,
  AlertTriangle,
  Calendar,
  BarChart3,
  BookOpen,
  Zap,
  ChevronUp,
  Brain,
  BookCopy
} from 'lucide-react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandInput, CommandGroup, CommandItem, CommandList } from "@/components/ui/command";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { cn } from "@/lib/utils";

// Using recharts instead of chart.js
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  LabelList
} from 'recharts';

// MultiSelect Component
const MultiSelect = ({ options, value, onChange, placeholder, disabled }) => {
  const [open, setOpen] = useState(false);

  const selectedOptions = useMemo(() => {
    return options.filter(option => value.includes(option.value));
  }, [options, value]);

  const handleSelect = (optionValue) => {
    const newValue = value.includes(optionValue)
      ? value.filter((val) => val !== optionValue)
      : [...value, optionValue];
    onChange(newValue);
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-full justify-between"
          disabled={disabled}
        >
          <div className="flex flex-wrap gap-1">
            {selectedOptions.length === 0 ? (
              <span className="text-muted-foreground">{placeholder}</span>
            ) : (
              selectedOptions.map((option) => (
                <Badge key={option.value} variant="secondary">
                  {option.label}
                  <button
                    type="button"
                    className="ml-1 text-xs"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleSelect(option.value);
                    }}
                  >
                    ×
                  </button>
                </Badge>
              ))
            )}
          </div>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
        <Command>
          <CommandInput placeholder="搜索选项..." />
          <CommandEmpty>未找到结果。</CommandEmpty>
          <CommandList>
            <CommandGroup>
              {options.map((option) => (
                <CommandItem
                  key={option.value}
                  onSelect={() => handleSelect(option.value)}
                >
                  <Check
                    className={cn(
                      "mr-2 h-4 w-4",
                      value.includes(option.value) ? "opacity-100" : "opacity-0"
                    )}
                  />
                  {option.label}
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};

// MeasuresEditor component
const MeasuresEditor = ({ measures, measureType, title, icon: Icon, onChange, disabled }) => {
  const addMeasure = () => {
    onChange([...measures, '']);
  };

  const updateMeasure = (measureIndex, value) => {
    const newMeasures = [...measures];
    newMeasures[measureIndex] = value;
    onChange(newMeasures);
  };

  const removeMeasure = (measureIndex) => {
    const newMeasures = measures.filter((_, i) => i !== measureIndex);
    onChange(newMeasures);
  };

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Icon className="w-4 h-4 text-blue-600" />
          <span className="font-medium">{title}</span>
        </div>
        <Button
          type="button"
          size="sm"
          variant="outline"
          onClick={addMeasure}
          disabled={disabled}
        >
          <Plus className="w-3 h-3 mr-1" />
          添加
        </Button>
      </div>
      <div className="space-y-2">
        {measures.map((measure, measureIndex) => (
          <div key={measureIndex} className="flex items-center gap-2">
            <Input
              value={measure}
              onChange={(e) => updateMeasure(measureIndex, e.target.value)}
              placeholder={`输入${title}...`}
              disabled={disabled}
            />
            <Button
              type="button"
              variant="ghost"
              size="icon"
              onClick={() => removeMeasure(measureIndex)}
              className="text-red-500 hover:text-red-700"
              disabled={disabled}
            >
              <Trash2 className="w-3 h-3" />
            </Button>
          </div>
        ))}
      </div>
    </div>
  );
};

// ResourceEditor component
const ResourceEditor = ({ resources, resourceType, title, icon: Icon, fields, onChange, disabled }) => {
  const addResource = () => {
    const newResource = fields.reduce((acc, field) => {
      acc[field.key] = field.type === 'number' ? 0 : '';
      return acc;
    }, {});
    onChange([...resources, newResource]);
  };

  const updateResource = (resourceIndex, field, value) => {
    const newResources = [...resources];
    newResources[resourceIndex] = {
      ...newResources[resourceIndex],
      [field]: field.includes('quantity') || field.includes('rate') || field.includes('cost') ?
        parseFloat(value) || 0 : value
    };
    onChange(newResources);
  };

  const removeResource = (resourceIndex) => {
    const newResources = resources.filter((_, i) => i !== resourceIndex);
    onChange(newResources);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Icon className="w-4 h-4 text-blue-600" />
          <span className="font-medium">{title}</span>
        </div>
        <Button
          type="button"
          size="sm"
          variant="outline"
          onClick={addResource}
          disabled={disabled}
        >
          <Plus className="w-3 h-3 mr-1" />
          添加
        </Button>
      </div>
      {resources.length > 0 && (
        <div className="border rounded-md overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                {fields.map(field => <TableHead key={field.key}>{field.label}</TableHead>)}
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {resources.map((resource, resourceIndex) => (
                <TableRow key={resourceIndex}>
                  {fields.map(field => (
                    <TableCell key={field.key}>
                      <Input
                        type={field.type || 'text'}
                        value={resource[field.key] || ''}
                        onChange={(e) => updateResource(resourceIndex, field.key, e.target.value)}
                        placeholder={field.placeholder}
                        className="min-w-0"
                        disabled={disabled}
                      />
                    </TableCell>
                  ))}
                  <TableCell>
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => removeResource(resourceIndex)}
                      className="text-red-500 hover:text-red-700"
                      disabled={disabled}
                    >
                      <Trash2 className="w-3 h-3" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}
    </div>
  );
};

// StandardWorkCategoriesEditor
const StandardWorkCategoriesEditor = ({ categories, onChange, disabled }) => {
  const addCategory = (category) => {
    if (!categories.includes(category)) {
      onChange([...categories, category]);
    }
  };

  const removeCategory = (category) => {
    onChange(categories.filter(c => c !== category));
  };

  const availableCategories = [
    '基础工程', '杆塔组立', '架线工程', '带电作业',
    '运输作业', '环境作业', '管理作业'
  ];

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <BookOpen className="w-4 h-4 text-blue-600" />
          <span className="font-medium">标准作业类别</span>
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        {categories.map(category => (
          <Badge key={category} variant="secondary" className="flex items-center gap-1">
            {category}
            {!disabled && (
              <button
                type="button"
                onClick={() => removeCategory(category)}
                className="ml-1 hover:text-red-500"
              >
                ×
              </button>
            )}
          </Badge>
        ))}
      </div>

      {!disabled && (
        <Popover>
          <PopoverTrigger asChild>
            <Button variant="outline" size="sm">
              <Plus className="w-3 h-3 mr-1" />
              添加类别
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-80">
            <Command>
              <CommandInput placeholder="搜索标准作业类别..." />
              <CommandEmpty>未找到相关类别</CommandEmpty>
              <CommandList>
                <CommandGroup>
                  {availableCategories
                    .filter(cat => !categories.includes(cat))
                    .map(category => (
                      <CommandItem
                        key={category}
                        onSelect={() => addCategory(category)}
                      >
                        <Check className={`mr-2 h-4 w-4 ${categories.includes(category) ? 'opacity-100' : 'opacity-0'}`} />
                        {category}
                      </CommandItem>
                    ))
                  }
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
      )}
    </div>
  );
};

// RiskPointsEditor
const RiskPointsEditor = ({ riskCodes, availableRisks, onChange, disabled }) => {
  const addRiskCode = (riskCode) => {
    if (!riskCodes.includes(riskCode)) {
      onChange([...riskCodes, riskCode]);
    }
  };

  const removeRiskCode = (riskCode) => {
    onChange(riskCodes.filter(code => code !== riskCode));
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Zap className="w-4 h-4 text-red-600" />
          <span className="font-medium">关联危险点</span>
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        {riskCodes.map(riskCode => {
          const riskPoint = availableRisks?.find(risk => risk.risk_code === riskCode);
          return (
            <Badge key={riskCode} variant="destructive" className="flex items-center gap-1">
              {riskPoint?.risk_name || riskCode}
              {!disabled && (
                <button
                  type="button"
                  onClick={() => removeRiskCode(riskCode)}
                  className="ml-1 hover:text-red-300"
                >
                  ×
                </button>
              )}
            </Badge>
          );
        })}
      </div>

      {!disabled && availableRisks && (
        <Popover>
          <PopoverTrigger asChild>
            <Button variant="outline" size="sm">
              <Plus className="w-3 h-3 mr-1" />
              添加危险点
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-96">
            <Command>
              <CommandInput placeholder="搜索危险点..." />
              <CommandEmpty>未找到相关危险点</CommandEmpty>
              <CommandList>
                <CommandGroup>
                  {availableRisks
                    .filter(risk => !riskCodes.includes(risk.risk_code))
                    .slice(0, 20)
                    .map(risk => (
                      <CommandItem
                        key={risk.risk_code}
                        onSelect={() => addRiskCode(risk.risk_code)}
                        className="flex flex-col items-start"
                      >
                        <div className="flex items-center w-full">
                          <Check className={`mr-2 h-4 w-4 ${riskCodes.includes(risk.risk_code) ? 'opacity-100' : 'opacity-0'}`} />
                          <div>
                            <div className="font-medium">{risk.risk_name}</div>
                            <div className="text-xs text-gray-500">{risk.risk_code} | {risk.primary_category}</div>
                          </div>
                        </div>
                      </CommandItem>
                    ))
                  }
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
      )}
    </div>
  );
};

// SortableStepItem component using @hello-pangea/dnd
const SortableStepItem = ({ id, step, index, onUpdateStepField, onUpdateStepResources, onRemove, availableStandards, availableRisks, onRiskChange, allSteps }) => {
  const [isExpanded, setIsExpanded] = useState(false);

  useEffect(() => {
    if (String(id).startsWith('new-')) {
      setIsExpanded(true);
    }
  }, [id]);

  const toggleExpansion = () => {
    setIsExpanded(prev => !prev);
  };

  const generateResourceTooltip = (resources, type) => {
    if (!resources || resources.length === 0) return "无";
    return resources.map((resource) => {
      switch (type) {
        case 'materials': return `${resource.name || '未知'} ${resource.specification || ''} ${resource.unit || ''} ${resource.quantity || 0}`;
        case 'personnel': return `${resource.role || '未知'} ${resource.quantity || 0}人 (${resource.qualification || '无要求'})`;
        case 'equipment': return `${resource.name || '未知'} ${resource.specification || ''} ${resource.unit || ''} ${resource.quantity || 0}`;
        case 'vehicles': return `${resource.type || '未知'} ${resource.quantity || 0}辆 (${resource.license_plate ? resource.license_plate : '无车牌'})`;
        default: return '';
      }
    }).join('\n');
  };

  const availableStepsForPredecessor = allSteps.filter((_, i) => i < index);

  return (
    <Draggable draggableId={String(id)} index={index}>
      {(provided, snapshot) => (
        <div
          ref={provided.innerRef}
          {...provided.draggableProps}
          className={`mb-4 ${snapshot.isDragging ? 'transform rotate-2' : ''}`}
        >
          <Card className="rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow">
            <CardHeader
              className="flex flex-row items-center justify-between p-4 bg-gray-50 hover:bg-gray-100 cursor-pointer"
              onClick={toggleExpansion}
            >
              <div className="flex items-center gap-3">
                <div {...provided.dragHandleProps} className="cursor-grab text-gray-400 hover:text-gray-600">
                  <GripVertical className="w-4 h-4" />
                </div>
                <div className="flex items-center gap-2">
                  {isExpanded ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
                  <span className="font-bold text-blue-600">#{step.step_order}</span>
                  <span className="font-medium">{step.step_name || '未命名步骤'}</span>
                </div>
              </div>
              <div className="flex items-center gap-4">
                <div className="hidden md:flex items-center gap-4 text-sm text-gray-600">
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-1 cursor-help">
                        <Clock className="w-3 h-3" />
                        <span>{step.duration_days || 0}天</span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>预计工期: {step.duration_days || 0} 天</p>
                    </TooltipContent>
                  </Tooltip>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-1 cursor-help">
                        <Package className="w-3 h-3" />
                        <span>{(step.required_materials || []).length}</span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-xs">
                      <p className="font-medium">所需物料 ({(step.required_materials || []).length}项):</p>
                      <pre className="text-xs whitespace-pre-wrap mt-1">
                        {generateResourceTooltip(step.required_materials, 'materials')}
                      </pre>
                    </TooltipContent>
                  </Tooltip>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-1 cursor-help">
                        <Users className="w-3 h-3" />
                        <span>{(step.required_personnel || []).length}</span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-xs">
                      <p className="font-medium">所需人员 ({(step.required_personnel || []).length}项):</p>
                      <pre className="text-xs whitespace-pre-wrap mt-1">
                        {generateResourceTooltip(step.required_personnel, 'personnel')}
                      </pre>
                    </TooltipContent>
                  </Tooltip>
                </div>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={(e) => {
                    e.stopPropagation();
                    onRemove(index);
                  }}
                  className="text-red-500 hover:text-red-700"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            </CardHeader>
            {!isExpanded && (
              <CardContent className="p-4 pt-2">
                <div className="pl-8 pr-4 space-y-2">
                  {step.description && (
                    <p className="text-sm text-gray-600 line-clamp-2">{step.description}</p>
                  )}
                  {(step.predecessor_steps || []).length > 0 && (
                    <div className="flex items-center gap-2">
                      <Calendar className="w-3 h-3 text-gray-500" />
                      <span className="text-xs font-medium text-gray-600">依赖:</span>
                      <div className="flex flex-wrap gap-1">
                        {(step.predecessor_steps || []).map(p => (
                          <Badge key={p} variant="secondary" className="text-xs">
                            步骤 #{p}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                  {(step.standard_work_categories || []).length > 0 && (
                    <div className="flex items-center gap-2">
                      <BookOpen className="w-3 h-3 text-blue-500" />
                      <span className="text-xs font-medium text-gray-600">作业类别:</span>
                      <div className="flex flex-wrap gap-1">
                        {(step.standard_work_categories || []).slice(0, 3).map(category => (
                          <Badge key={category} variant="outline" className="text-xs">
                            {category}
                          </Badge>
                        ))}
                        {(step.standard_work_categories || []).length > 3 && (
                          <Badge variant="outline" className="text-xs">
                            +{(step.standard_work_categories || []).length - 3}
                          </Badge>
                        )}
                      </div>
                    </div>
                  )}
                  {(step.associated_risk_codes || []).length > 0 && (
                    <div className="flex items-center gap-2">
                      <Zap className="w-3 h-3 text-red-500" />
                      <span className="text-xs font-medium text-gray-600">危险点:</span>
                      <div className="flex flex-wrap gap-1">
                        {(step.associated_risk_codes || []).slice(0, 2).map(riskCode => {
                          const riskPoint = availableRisks?.find(risk => risk.risk_code === riskCode);
                          return (
                            <Badge key={riskCode} variant="destructive" className="text-xs">
                              {riskPoint?.risk_name || riskCode}
                            </Badge>
                          );
                        })}
                        {(step.associated_risk_codes || []).length > 2 && (
                          <Badge variant="destructive" className="text-xs">
                            +{(step.associated_risk_codes || []).length - 2}
                          </Badge>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            )}

            {isExpanded && (
              <CardContent className="border-t bg-gray-50 p-4">
                <div className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <Label className="text-sm font-medium">步骤名称</Label>
                      <Input
                        value={step.step_name}
                        onChange={(e) => onUpdateStepField(index, 'step_name', e.target.value)}
                        placeholder="例如: 搭设跨越架"
                      />
                    </div>
                    <div>
                      <Label className="text-sm font-medium">工期 (天)</Label>
                      <Input
                        type="number"
                        min="0.1"
                        step="0.1"
                        value={step.duration_days}
                        onChange={(e) => onUpdateStepField(index, 'duration_days', parseFloat(e.target.value) || 0)}
                        placeholder="1"
                      />
                    </div>
                    <div>
                      <Label className="text-sm font-medium">人员数量</Label>
                      <Input
                        type="number"
                        value={step.personnel_count || 0}
                        onChange={(e) => onUpdateStepField(index, 'personnel_count', parseFloat(e.target.value) || 0)}
                        placeholder="0"
                      />
                    </div>
                  </div>

                  <div>
                    <Label className="block text-sm font-medium mb-2 flex items-center gap-1">
                      <Calendar className="w-4 h-4" />
                      前置步骤依赖
                    </Label>
                    {availableStepsForPredecessor.length > 0 ? (
                      <div className="grid grid-cols-2 md:grid-cols-3 gap-2 p-3 bg-gray-50 rounded-lg border">
                        {availableStepsForPredecessor.map((predStep) => {
                          const predStepNumber = predStep.step_order;
                          return (
                            <label key={predStepNumber} className="flex items-center space-x-2 cursor-pointer">
                              <input
                                type="checkbox"
                                checked={(step.predecessor_steps || []).includes(predStepNumber)}
                                onChange={(e) => {
                                  const currentPredecessors = step.predecessor_steps || [];
                                  let newPredecessors;
                                  if (e.target.checked) {
                                    newPredecessors = [...currentPredecessors, predStepNumber];
                                  } else {
                                    newPredecessors = currentPredecessors.filter(p => p !== predStepNumber);
                                  }
                                  onUpdateStepField(index, 'predecessor_steps', newPredecessors);
                                }}
                                className="rounded border-gray-300"
                              />
                              <span className="text-sm">步骤{predStepNumber}: {predStep.step_name}</span>
                            </label>
                          );
                        })}
                      </div>
                    ) : (
                      <p className="text-sm text-gray-500 p-3 bg-gray-50 rounded-lg border">
                        无可选前置步骤（当前为第{step.step_order}个步骤）
                      </p>
                    )}
                  </div>

                  <div>
                    <Label className="text-sm font-medium">工作内容描述</Label>
                    <Textarea
                      value={step.description}
                      onChange={(e) => onUpdateStepField(index, 'description', e.target.value)}
                      placeholder="详细描述此步骤的工作内容和要求"
                      rows={3}
                    />
                  </div>

                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 p-4 bg-blue-50 rounded-lg border border-blue-200">
                    <StandardWorkCategoriesEditor
                      categories={step.standard_work_categories || []}
                      onChange={(val) => onUpdateStepField(index, 'standard_work_categories', val)}
                    />
                    <RiskPointsEditor
                      riskCodes={step.associated_risk_codes || []}
                      availableRisks={availableRisks}
                      onChange={(val) => onRiskChange(index, val)}
                    />
                  </div>

                  <Tabs defaultValue="materials" className="w-full">
                    <TabsList className="grid w-full grid-cols-4 md:grid-cols-8">
                      <TabsTrigger value="materials">物料</TabsTrigger>
                      <TabsTrigger value="personnel">人员</TabsTrigger>
                      <TabsTrigger value="equipment">工器具</TabsTrigger>
                      <TabsTrigger value="vehicles">车辆</TabsTrigger>
                      <TabsTrigger value="technical">技术</TabsTrigger>
                      <TabsTrigger value="safety">安全</TabsTrigger>
                      <TabsTrigger value="quality">质量</TabsTrigger>
                      <TabsTrigger value="environmental">环保</TabsTrigger>
                    </TabsList>
                    <TabsContent value="materials" className="mt-4">
                      <ResourceEditor
                        resources={step.required_materials || []}
                        resourceType="required_materials"
                        title="所需物料"
                        icon={Package}
                        fields={[
                          { key: 'name', label: '名称', placeholder: '物料名称' },
                          { key: 'specification', label: '规格', placeholder: '规格型号' },
                          { key: 'unit', label: '单位', placeholder: '单位' },
                          { key: 'quantity', label: '数量', type: 'number', placeholder: '数量' }
                        ]}
                        onChange={(val) => onUpdateStepResources(index, 'required_materials', val)}
                      />
                    </TabsContent>
                    <TabsContent value="personnel" className="mt-4">
                      <ResourceEditor
                        resources={step.required_personnel || []}
                        resourceType="required_personnel"
                        title="所需人员"
                        icon={Users}
                        fields={[
                          { key: 'role', label: '工种/岗位', placeholder: '工种岗位' },
                          { key: 'quantity', label: '人数', type: 'number', placeholder: '人数' },
                          { key: 'qualification', label: '资质要求', placeholder: '资质要求' }
                        ]}
                        onChange={(val) => onUpdateStepResources(index, 'required_personnel', val)}
                      />
                    </TabsContent>
                    <TabsContent value="equipment" className="mt-4">
                      <ResourceEditor
                        resources={step.required_equipment || []}
                        resourceType="required_equipment"
                        title="所需工器具"
                        icon={Wrench}
                        fields={[
                          { key: 'name', label: '名称', placeholder: '工器具名称' },
                          { key: 'specification', label: '规格', placeholder: '规格型号' },
                          { key: 'unit', label: '单位', placeholder: '单位' },
                          { key: 'quantity', label: '数量', type: 'number', placeholder: '数量' }
                        ]}
                        onChange={(val) => onUpdateStepResources(index, 'required_equipment', val)}
                      />
                    </TabsContent>
                    <TabsContent value="vehicles" className="mt-4">
                      <ResourceEditor
                        resources={step.required_vehicles || []}
                        resourceType="required_vehicles"
                        title="所需车辆"
                        icon={Truck}
                        fields={[
                          { key: 'type', label: '类型', placeholder: '车辆类型' },
                          { key: 'license_plate', label: '车牌号', placeholder: '可选' },
                          { key: 'quantity', label: '数量', type: 'number', placeholder: '数量' }
                        ]}
                        onChange={(val) => onUpdateStepResources(index, 'required_vehicles', val)}
                      />
                    </TabsContent>
                    <TabsContent value="technical" className="mt-4">
                      <MeasuresEditor measures={step.technical_measures || []} measureType="technical_measures" title="技术措施" icon={Wrench} onChange={(val) => onUpdateStepResources(index, 'technical_measures', val)} />
                    </TabsContent>
                    <TabsContent value="safety" className="mt-4">
                      <MeasuresEditor measures={step.safety_measures || []} measureType="safety_measures" title="安全措施" icon={Shield} onChange={(val) => onUpdateStepResources(index, 'safety_measures', val)} />
                    </TabsContent>
                    <TabsContent value="quality" className="mt-4">
                      <MeasuresEditor measures={step.quality_measures || []} measureType="quality_measures" title="质量措施" icon={CheckSquare} onChange={(val) => onUpdateStepResources(index, 'quality_measures', val)} />
                    </TabsContent>
                    <TabsContent value="environmental" className="mt-4">
                      <MeasuresEditor measures={step.environmental_measures || []} measureType="environmental_measures" title="环保措施" icon={Leaf} onChange={(val) => onUpdateStepResources(index, 'environmental_measures', val)} />
                    </TabsContent>
                  </Tabs>
                </div>
              </CardContent>
            )}
          </Card>
        </div>
      )}
    </Draggable>
  );
};

function StepsManager({ scheme, onUpdate, availableStandards, availableRisks }) {
  const [editedSteps, setEditedSteps] = useState([]);
  const [showGantt, setShowGantt] = useState(false);

  useEffect(() => {
    // 确保完整复制施工步骤数据，包括所有措施字段
    const stepsData = scheme.construction_steps || [];
    const completeSteps = stepsData.map(step => ({
      id: step.id || `step-${step.step_order}-${Date.now()}`,
      step_order: step.step_order || 1,
      step_name: step.step_name || '',
      description: step.description || '',
      duration_days: step.duration_days || 1, // Changed from duration_hours to duration_days
      personnel_count: step.personnel_count || 0,
      predecessor_steps: Array.isArray(step.predecessor_steps) ? [...step.predecessor_steps] : [],
      // 确保所有措施数组都被正确初始化和复制
      technical_measures: Array.isArray(step.technical_measures) ? [...step.technical_measures] : [],
      safety_measures: Array.isArray(step.safety_measures) ? [...step.safety_measures] : [],
      quality_measures: Array.isArray(step.quality_measures) ? [...step.quality_measures] : [],
      environmental_measures: Array.isArray(step.environmental_measures) ? [...step.environmental_measures] : [],
      // 确保资源数据完整复制
      required_materials: Array.isArray(step.required_materials) ? JSON.parse(JSON.stringify(step.required_materials)) : [],
      required_personnel: Array.isArray(step.required_personnel) ? JSON.parse(JSON.stringify(step.required_personnel)) : [],
      required_equipment: Array.isArray(step.required_equipment) ? JSON.parse(JSON.stringify(step.required_equipment)) : [],
      required_vehicles: Array.isArray(step.required_vehicles) ? JSON.parse(JSON.stringify(step.required_vehicles)) : [],
      // 确保标准作业类别和风险代码完整复制
      standard_work_categories: Array.isArray(step.standard_work_categories) ? [...step.standard_work_categories] : [],
      associated_risk_codes: Array.isArray(step.associated_risk_codes) ? [...step.associated_risk_codes] : []
    }));
    
    console.log('StepsManager 加载步骤数据:', completeSteps); // 调试日志
    setEditedSteps(completeSteps);
  }, [scheme.construction_steps]);

  const recalculateMeasures = useCallback((currentSteps, currentSchemeSafetyMeasures) => {
    const allPossibleMeasuresFromKB = new Set(
      (availableRisks || []).flatMap(r => r.control_measures || [])
    );

    const manualMeasures = (currentSchemeSafetyMeasures || []).filter(
      m => !allPossibleMeasuresFromKB.has(m)
    );

    const allSelectedRiskCodes = new Set(
      currentSteps.flatMap(step => step.associated_risk_codes || [])
    );

    const newGeneratedMeasures = new Set();
    allSelectedRiskCodes.forEach(code => {
      const riskPoint = (availableRisks || []).find(r => r.risk_code === code);
      if (riskPoint && riskPoint.control_measures) {
        riskPoint.control_measures.forEach(measure => newGeneratedMeasures.add(measure));
      }
    });

    const finalMeasures = [...new Set([...manualMeasures, ...Array.from(newGeneratedMeasures)])];

    onUpdate({
      ...scheme,
      construction_steps: currentSteps, // 确保步骤数据也被更新
      scheme_level_safety_measures: finalMeasures
    });
  }, [availableRisks, onUpdate, scheme]);

  const handleDragEnd = (result) => {
    if (!result.destination) {
      return;
    }

    const newSteps = Array.from(editedSteps);
    const [removed] = newSteps.splice(result.source.index, 1);
    newSteps.splice(result.destination.index, 0, removed);

    const reorderedSteps = newSteps.map((step, index) => ({
      ...step, // 保持所有现有字段
      step_order: index + 1
    }));
    
    console.log('拖拽重排后的步骤:', reorderedSteps); // 调试日志
    setEditedSteps(reorderedSteps);
    onUpdate({ ...scheme, construction_steps: reorderedSteps });
  };

  const handleUpdateStepField = (indexToUpdate, field, value) => {
    const newSteps = editedSteps.map((step, idx) =>
      idx === indexToUpdate
        ? { ...step, [field]: value } // 保持所有现有字段
        : step
    );
    
    console.log(`更新步骤字段 [${indexToUpdate}].${field}:`, value); // 调试日志
    setEditedSteps(newSteps);
    onUpdate({ ...scheme, construction_steps: newSteps });
  };

  const handleUpdateStepResources = (indexToUpdate, resourceType, resources) => {
    const newSteps = editedSteps.map((step, idx) =>
      idx === indexToUpdate
        ? { ...step, [resourceType]: resources } // 保持所有现有字段
        : step
    );
    
    console.log(`更新步骤资源 [${indexToUpdate}].${resourceType}:`, resources); // 调试日志
    setEditedSteps(newSteps);
    onUpdate({ ...scheme, construction_steps: newSteps });
  };

  const handleAddStep = () => {
    const newStep = {
      id: `new-${Date.now()}`,
      step_order: editedSteps.length + 1,
      step_name: '新步骤',
      description: '',
      duration_days: 1, // Changed from duration_hours to duration_days
      personnel_count: 0,
      predecessor_steps: [],
      // 确保新步骤包含所有必要的字段
      required_materials: [],
      required_personnel: [],
      required_equipment: [],
      required_vehicles: [],
      technical_measures: [],
      safety_measures: [],
      quality_measures: [],
      environmental_measures: [],
      standard_work_categories: [],
      associated_risk_codes: [],
    };
    
    const newSteps = [...editedSteps, newStep];
    console.log('添加新步骤:', newStep); // 调试日志
    setEditedSteps(newSteps);
    onUpdate({ ...scheme, construction_steps: newSteps });
  };

  const handleRemoveStep = (indexToRemove) => {
    const newSteps = editedSteps.filter((_, index) => index !== indexToRemove)
      .map((step, index) => ({ 
        ...step, // 保持所有现有字段
        step_order: index + 1 
      }));
    
    console.log('删除步骤后:', newSteps); // 调试日志
    setEditedSteps(newSteps);
    recalculateMeasures(newSteps, scheme.scheme_level_safety_measures);
  };

  const handleRiskChange = (stepIndex, selectedRiskCodes) => {
    const newSteps = editedSteps.map((step, index) =>
      index === stepIndex
        ? { ...step, associated_risk_codes: selectedRiskCodes } // 保持所有现有字段
        : step
    );
    
    console.log(`更新步骤风险代码 [${stepIndex}]:`, selectedRiskCodes); // 调试日志
    setEditedSteps(newSteps);
    recalculateMeasures(newSteps, scheme.scheme_level_safety_measures);
  };

  const ganttData = useMemo(() => {
    const calculateSchedule = (steps) => {
        if (!steps || !steps.length) return [];
        
        let schedule = steps.map(s => ({
            ...s,
            duration_days: s.duration_days || 1, // Directly use duration_days
            start_day: 0,
            end_day: 0
        }));

        let scheduledCount = 0;
        let iterations = 0;

        // Iterate until all steps are scheduled or max iterations reached (to prevent infinite loops)
        while(scheduledCount < schedule.length && iterations < schedule.length * 2) {
            let newScheduledInLoop = false;
            for (const step of schedule) {
                if (step.start_day > 0) continue; // Already scheduled

                const predecessors = step.predecessor_steps || [];
                let dependenciesMet = true;
                let maxPredecessorEndDay = 0;

                for (const predOrder of predecessors) {
                    const predStep = schedule.find(s => s.step_order === predOrder);
                    if (!predStep || predStep.start_day === 0) { // Predecessor not scheduled yet
                        dependenciesMet = false;
                        break;
                    }
                    maxPredecessorEndDay = Math.max(maxPredecessorEndDay, predStep.end_day);
                }

                if (dependenciesMet) {
                    step.start_day = maxPredecessorEndDay + 1; // Start day is after all predecessors finish
                    if (predecessors.length === 0) { // If no predecessors, start on day 1
                        step.start_day = 1;
                    }
                    step.end_day = step.start_day + step.duration_days - 1;
                    scheduledCount++;
                    newScheduledInLoop = true;
                }
            }
            if (!newScheduledInLoop && scheduledCount < schedule.length) {
                // No new steps could be scheduled in this loop, but not all are scheduled.
                // This indicates a potential dependency cycle or unresolvable dependencies.
                // Force remaining unscheduled steps to start on day 1 to avoid infinite loop.
                console.error("无法安排所有步骤，可能存在依赖循环或未满足的依赖。");
                schedule.filter(s => s.start_day === 0).forEach(s => {
                    s.start_day = 1;
                    s.end_day = s.duration_days;
                    scheduledCount++; // Mark as scheduled
                });
                break; // Exit loop after handling
            }
            iterations++;
        }

        schedule.sort((a, b) => a.start_day - b.start_day || a.step_order - b.step_order);
        return schedule;
    };

    const scheduledSteps = calculateSchedule(editedSteps);
    
    return scheduledSteps.map(step => ({
      name: `${step.step_order}. ${step.step_name}`,
      // 'start' for recharts is the transparent bar's length to offset the actual bar
      start: step.start_day > 1 ? step.start_day - 1 : 0, 
      duration: step.duration_days,
      startDay: step.start_day,
      endDay: step.end_day,
      // Removed duration_hours, now only duration_days is used
    }));
  }, [editedSteps]);

  const CustomBarLabel = ({ x, y, width, height, value, payload }) => {
    // Add safety checks
    if (!payload || !payload.name || width < 60) return null;
    
    const name = payload.name.split('. ').slice(1).join('. ');
    const displayName = name.length > 20 ? `${name.substring(0, 18)}...` : name;
    
    return (
        <text 
          x={x + 10} 
          y={y + height / 2} 
          fill="#fff" 
          textAnchor="start" 
          dominantBaseline="middle" 
          fontSize={11} 
          fontWeight="500"
        >
            {`${displayName} (${value}天)`}
        </text>
    );
  };
  
  const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length && payload[0].payload) {
      const data = payload[0].payload;
      return (
        <div className="bg-white p-3 border rounded shadow-lg text-sm">
          <p className="font-bold mb-1">{data.name || '未知步骤'}</p>
          <p>开始: 第 {data.startDay || 0} 天</p>
          <p>结束: 第 {data.endDay || 0} 天</p>
          <p>工期: {data.duration || 0} 天</p> {/* Removed hours display */}
        </div>
      );
    }
    return null;
  };

  const totalManpowerDays = useMemo(() => {
    return editedSteps.reduce((sum, step) => sum + ((step.duration_days || 0) * (step.personnel_count || 0)), 0);
  }, [editedSteps]);

  const totalDurationGantt = useMemo(() => {
    return Math.max(...ganttData.map(d => d.endDay), 0);
  }, [ganttData]);


  return (
    <TooltipProvider>
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>施工步骤管理</CardTitle>
          <div className="flex items-center gap-2">
            <div className="flex items-center border rounded-lg p-1">
              <Button
                variant={!showGantt ? 'default' : 'ghost'}
                size="sm"
                onClick={() => setShowGantt(false)}
                className="h-8"
              >
                <Edit3 className="w-4 h-4 mr-1" />
                步骤详情
              </Button>
              <Button
                variant={showGantt ? 'default' : 'ghost'}
                size="sm"
                onClick={() => setShowGantt(true)}
                className="h-8"
              >
                <BarChart3 className="w-4 h-4 mr-1" />
                进度甘特图
              </Button>
            </div>
            <Button onClick={handleAddStep} variant="outline">
              <Plus className="w-4 h-4 mr-2" />
              添加步骤
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {!showGantt ? (
            editedSteps.length === 0 ? (
              <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                <p>暂无施工步骤</p>
                <Button onClick={handleAddStep} variant="outline" className="mt-2">
                  <Plus className="w-4 h-4 mr-2" />
                  添加第一个步骤
                </Button>
              </div>
            ) : (
              <DragDropContext onDragEnd={handleDragEnd}>
                <Droppable droppableId="steps">
                  {(provided) => (
                    <div {...provided.droppableProps} ref={provided.innerRef}>
                      {editedSteps.map((step, index) => (
                        <SortableStepItem
                          key={step.id || step.step_order}
                          id={step.id || step.step_order}
                          step={step}
                          index={index}
                          onUpdateStepField={handleUpdateStepField}
                          onUpdateStepResources={handleUpdateStepResources}
                          onRemove={handleRemoveStep}
                          availableStandards={availableStandards}
                          availableRisks={availableRisks}
                          onRiskChange={handleRiskChange}
                          allSteps={editedSteps}
                        />
                      ))}
                      {provided.placeholder}
                    </div>
                  )}
                </Droppable>
              </DragDropContext>
            )
          ) : (
            <div className="space-y-4">
              <div className="h-[600px] w-full bg-gray-50/50 p-4 rounded-lg border">
                {editedSteps.length > 0 ? (
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart
                      data={ganttData.slice().reverse()} // Reverse data to show step 1 at the top
                      layout="vertical"
                      margin={{ top: 5, right: 30, left: 100, bottom: 20 }}
                      barCategoryGap="35%" // Space between bars
                    >
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis 
                        type="number" 
                        domain={[0, dataMax => (Math.ceil((dataMax + 2)/5)*5)]} // Ensure axis ends on a multiple of 5, with some padding
                        label={{ value: '天数', position: 'insideBottom', offset: -10, dy: 10 }}
                        tickFormatter={(value) => `${value}天`}
                      />
                      <YAxis 
                        dataKey="name" 
                        type="category" 
                        width={120} 
                        tick={{ fontSize: 11 }} 
                        interval={0} // Show all labels
                      />
                      <RechartsTooltip content={<CustomTooltip />} cursor={{fill: 'rgba(200, 200, 200, 0.1)'}}/>
                      <Legend verticalAlign="top" wrapperStyle={{ paddingBottom: '15px' }}/>
                      {/* Transparent bar for offset */}
                      <Bar dataKey="start" stackId="a" fill="transparent" legendType="none" /> 
                      {/* Actual duration bar */}
                      <Bar dataKey="duration" stackId="a" fill="#3b82f6" name="工期" radius={[0, 4, 4, 0]}>
                        <LabelList dataKey="duration" content={CustomBarLabel} />
                      </Bar>
                    </BarChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg flex flex-col items-center justify-center h-full">
                    <BarChart3 className="w-16 h-16 text-gray-300 mb-4"/>
                    <p>请添加施工步骤以显示甘特图。</p>
                  </div>
                )}
              </div>
              <div className="flex flex-col md:flex-row gap-2 md:gap-4 text-sm text-gray-600">
                <Badge variant="outline" className="text-xs">
                  总工期估算: {totalDurationGantt} 天
                </Badge>
                <Badge variant="outline" className="text-xs">
                  总人力: {totalManpowerDays} 人·天
                </Badge>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </TooltipProvider>
  );
}

export default StepsManager;
